#include "ts.hpp"
using namespace std;
using std::placeholders::_1;
using std::placeholders::_2;
ts::ts(std::string name):
    rclcpp::Node(name)
{
    puber = this->create_publisher<std_msgs::msg::String>("ts",10);
    suber = this->create_subscription<std_msgs::msg::String>("ts",10,
                                                             std::bind(&ts::suber_callback,this,_1));
    group_ = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
    timer_ = this->create_wall_timer(std::chrono::milliseconds(100),
                                     std::bind(&ts::timer_callback,this),group_);


    client_ = this->create_client<ts_test::srv::Test>("ser",rmw_qos_profile_services_default,group_);
    service_ = this->create_service<ts_test::srv::Test>("ser",
                                                        std::bind(&ts::seriver_callback,this,_1,_2),
                                                        rmw_qos_profile_services_default,
                                                        group_);
    RCLCPP_INFO(this->get_logger(),"node name:%s",name.c_str());
}

ts::~ts()
{

}

void ts::timer_callback()
{
    std_msgs::msg::String str;
    static int count=1;
    std::string s = "ts"+std::string('a',count++);
    str.data = s;
    if(count>5)count = 1;
//    RCLCPP_INFO(this->get_logger(),"publish mes");
    puber->publish(str);

    while(!client_->wait_for_service(std::chrono::milliseconds(10000))){

    };
    auto req = std::make_shared<ts_test::srv::Test::Request>();
    req->a = count;
    req->b = count*count;
    client_->async_send_request(req,std::bind(&ts::clicent_callback,this,_1));
}

void ts::suber_callback(std_msgs::msg::String str)
{
    RCLCPP_INFO(this->get_logger(),"%s",str.data.c_str());
}

void ts::seriver_callback(const std::shared_ptr<ts_test::srv::Test::Request> request,
                          std::shared_ptr<ts_test::srv::Test::Response> response)
{
    response->sum = request->a+request->b;
}

void ts::clicent_callback(rclcpp::Client<ts_test::srv::Test>::SharedFuture s)
{
   auto p = s.get();
   RCLCPP_INFO(this->get_logger(),"sum = %d",p->sum);

}


